<?php

namespace App\Console\Commands;
use App\Models\Game\LogRoleKill;
use App\Models\Game\MemberLtu;
use App\Models\Game\OnLine;
use App\Models\Game\RoleStall;
use App\Models\Game\Server;
use App\Utils\EsUtil;
use App\Utils\MyLog;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class OnlineTask extends Command //注册统计
{
    /**
     * The name and signature of the console command.
     * 统计客户留存数据
     *
     * @var string
     */
    protected $signature = 'command:OnlineTask';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
     // docker exec phpfpm bash -c "cd /xm2/code/laravelapp && php artisan command:OnlineTask 2023-09-26"
     // docker exec task bash -c "supervisorctl restart MemberLtuTask"

    public function handle()
    {
        go(function(){

            $divisor = 600; //10分钟的整数
            $this->moveToEs();
            while(true){
                $time = time();
                if ($time % $divisor === 0) {
                    $this->moveToEs();
                }
                \Swoole\Coroutine::sleep(1); // 休眠 10分钟
            }
        });
    }

    private function  moveToEs()
    {
        //获取当前可用服务器id
        $serverIds = Server::where('status', 1)->where('mysql_game_data_can_use', 1)->pluck('server_id');
        MyLog::info('服务器ID'.json_encode($serverIds));
        foreach ($serverIds as $serverId) {
            MyLog::info('没连接错误的服务器ID'.json_encode($serverId));
            if ($serverId == 100) {
                continue;
            }
            $onLineModel=new OnLine();
            $onLineModel->setConnection('function_'.$serverId);
            $result = $onLineModel->paginate()->first();

            $result->server_id = $serverId;
            $result->num = $result->onlines;
            $result->created_at = date("Y-m-d H:i:s");
            $result->save();
        }

    }
}
